package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 登录
     *
     * @param dto 登录信息
     */
    @Override
    public ResponseResult<Map<String, Object>> login(AdUserDto dto) {
        // 1.参数校验
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码为空");
        }

        // 2.查询用户信息
        AdUser adUser = lambdaQuery().eq(AdUser::getName, dto.getName()).one();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        System.out.println("查询用户信息: " + adUser);

        // 3.密码校验
        String salt = adUser.getSalt();
        String pw = dto.getPassword();
        pw = DigestUtils.md5DigestAsHex((pw + salt).getBytes());

        boolean isRight = verifyPw(salt, pw, adUser.getPassword());
        System.out.println("密码校验: " + isRight);
        if (isRight) {
            // 4.返回数据  jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user", adUser);
            return ResponseResult.okResult(map);

        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

    }

    /**
     * 校验密码
     *
     * @param salt           用于校验的 盐
     * @param password       前端传递的密码
     * @param adUserPassword 数据库中的密码
     */
    private boolean verifyPw(String salt, String password, String adUserPassword) {
        return adUserPassword.equals(
                DigestUtils.md5DigestAsHex((password + salt).getBytes()));
    }
}
